package com.limao.CacheManager;

import com.Hazelcast.Cache;
import com.Hazelcast.CacheFactory;
import com.limao.DBDataClass.UserNumDataClass;
import com.limao.DBProvider.UserNumProvider;
import com.limao.cache.BasicModule;

public class usernumCacheManager  extends BasicModule{

	private static final String key="userIdnum";
	
	private static usernumCacheManager instance;

    public static usernumCacheManager getInstance() {
        return instance;
    }

	private UserNumProvider provider;
	
    private Cache<String, UserNumDataClass> usernumCacheManagerCache;

    public usernumCacheManager() {
      	super("usernumCacheManager");
      	usernumCacheManagerCache = CacheFactory.createCache("cd_usernumCache");
        initProvider();
    }
    
    @Override
	public void initialize() {
        super.initialize();
        instance=this;
    }
    
    public void ClearObjectCache()
    {
    	UserNumDataClass obj =usernumCacheManagerCache.get(key);
    	if(obj!=null)
    	{
    		usernumCacheManagerCache.remove(key);
    	}
    }  
 
    
    //初始化，加载数据库
    public UserNumDataClass loadAlltoCache()
    {
    	ClearObjectCache();
    	UserNumDataClass obj =provider.Load_System_DB_All();
    	if(obj==null)
    		obj=provider.Create_System_DB_All();
    	if(obj!=null)
    		usernumCacheManagerCache.put(key, obj);
    	return obj;
    }
  //修改数据库
    public int ModifiedObjectCache()
    {
    	int num=1000;
    	UserNumDataClass obj=getObj();
        if(obj!=null)
        	num=obj.user_num;
        else
        	obj=new UserNumDataClass();
    	//先放缓存再存数据库,使得缓存中的userIdnum永远不会少于数据里的值
    	num=num+1;
    	obj.user_num=num;
    	usernumCacheManagerCache.put(key, obj);
    	
    	provider.Updata_System_DB_All(num);

    	return num;
    }
    //从缓存中得到数值
    public UserNumDataClass getObj() {
      	UserNumDataClass obj = usernumCacheManagerCache.get(key);
        if (obj == null) {
            synchronized (key.intern()) {
            	obj = usernumCacheManagerCache.get(key);
                if (obj == null) {
                	ClearObjectCache();
                	obj =loadAlltoCache();
                 }
            }
        }

        return obj;
    }
    
    
    
    
    private void initProvider() {
        if (provider == null ) {
            try {
                provider =UserNumProvider.getInstance();
            }
            catch (Exception e) {
            	e.printStackTrace();
            }
        }
    }
  
	
}
